package com.async_export_demo.controller;

import com.async_export_demo.export.AsyncExportService;
import com.async_export_demo.export.ExportEnum;
import com.async_export_demo.export.SyncExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;

@RestController
@RequestMapping(value = "/export")
public class ExportController {

    @Autowired
    private AsyncExportService asyncExportService;

    @Autowired
    private SyncExportService syncExportService;

    @GetMapping(value = "/exportAsync")
    public String exportData(@RequestParam("type") ExportEnum exportEnum) {
        BigInteger taskId = asyncExportService.asyncExport(exportEnum);
        return taskId.toString();
    }

    @GetMapping("/exportSync")
    public void exportSync(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试同步导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        syncExportService.syncExportOrder(response.getOutputStream());
    }

}
